package cn.virens;

import java.io.Serializable;
import java.util.function.Function;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

public class Redis {
	private RedisClient client;

	private static Redis redis = new Redis();
	private static RedisCode codec = new RedisCode();

	public static Redis redis() {
		return redis;
	}

	public RedisClient client() {
		if (client == null) {
			RedisURI.Builder builder = RedisURI.builder();
			builder.withHost("tx/virens.cn");
			builder.withPort(6379);
			builder.withDatabase(1);
			// builder.withPassword(passwrod);

			this.client = RedisClient.create(builder.build());
		}

		return client;
	}

	public <R> R connect(Function<RedisCommands<String, Serializable>, R> fun) {
		StatefulRedisConnection<String, Serializable> connection = null;
		RedisCommands<String, Serializable> commands = null;
		try {
			connection = client().connect(codec);
			commands = connection.sync();

			return fun.apply(commands);
		} finally {
			connection.close();
		}
	}

	public static void main(String[] args) {
		Redis.redis().connect((c) -> {
			System.out.println(c.get("WQ"));

			return null;
		});
	}
}
